package parser

import (
	"GoSpider/carwler/engine"
	"GoSpider/carwler/model"
	"bytes"
	"github.com/PuerkitoBio/goquery"
	log "github.com/sirupsen/logrus"
	"regexp"
	"strconv"
	"strings"
)

func ParseProfile(contents []byte, name ,url string) engine.ParseResult {

	defer func() {
		if err := recover(); err != nil {
			log.Warnf("parse profile err %s", err)
		}
	}()

	profile := model.Profile{}

	profile.Name = name
	bytesReader := bytes.NewReader(contents)
	document, err := goquery.NewDocumentFromReader(bytesReader)
	if err != nil {
		log.Warnf("parse profile read document err %s", err.Error())
	}

	text := document.Find("div.des").Text()
	array := strings.Split(text, "|")

	profile.Province = strings.Replace(array[0], " ", "", -1)

	ageRe := regexp.MustCompile(`([\d]+)岁`)
	ageSubMatch := ageRe.FindStringSubmatch(array[1])
	if age, err := strconv.Atoi(ageSubMatch[1]); err == nil {
		profile.Age = age
	}

	profile.Education = strings.Replace(array[2], " ", "", -1)
	profile.Marriage = strings.Replace(array[3], " ", "", -1)

	statureRe := regexp.MustCompile(`([\d]+)cm`)
	statureSubMatch := statureRe.FindStringSubmatch(array[4])
	if stature, err := strconv.Atoi(statureSubMatch[1]); err == nil {
		profile.Stature = stature
	}
	introduce := document.Find("div.m-content-box.m-des").Find("span").Text()
	profile.Introduce = strings.Replace(introduce, " ", "", -1)

	val, exists := document.Find("div.logo").Attr("style")
	if exists {
		left := strings.Index(val, "(")
		right := strings.Index(val, ")")
		profile.Avatar = val[left+1 : right]
	}

	// <div data-v-5b109fc3="" class="id">ID：1546044736</div>
	id := document.Find("div.id").Text()
	idRe := regexp.MustCompile(`ID：([\d]+)`)
	idSubmatch := idRe.FindStringSubmatch(id)
	id = strings.Replace(idSubmatch[1], " ", "", -1)

	result := engine.ParseResult{
		Items: []engine.Item{
			{
				Url:     url,
				Type:    "zhenai",
				Id:      id,
				Payload: profile,
			},
		},
	}
	return result
}
